package com.example.exam11;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ToggleButton;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    boolean isRegister;
    ToggleButton tglBtn;
    TextView tvLevel;
    BatteryReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tglBtn = findViewById(R.id.tgl_button);
        tvLevel = findViewById(R.id.tv_level);
        receiver = new BatteryReceiver();
        tglBtn.setOnCheckedChangeListener((compoundButton, isChecked) -> {
            if (isChecked) {
                IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
                registerReceiver(receiver, filter);
                isRegister = true;
            } else {
                unregisterReceiver(receiver);
                isRegister = false;
                tvLevel.setText("电量未知");
            }
        });
    }

    @Override
    protected void onStop() {
        if (isRegister) {
            unregisterReceiver(receiver);
        }
        super.onStop();
    }

    private class BatteryReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int current = intent.getExtras().getInt("level");
            int total = intent.getExtras().getInt("scale");
            int percent = current * 100 / total;
            tvLevel.setText("当前手机电量是：" + percent + "%");
        }
    }
}
